<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.json.*" %>
<%@ page import="net.sourceforge.pinyin4j.PinyinHelper" %>
<%@ page import="net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat" %>
<%@ page import="net.sourceforge.pinyin4j.format.HanyuPinyinCaseType" %>
<%@ page import="net.sourceforge.pinyin4j.format.HanyuPinyinToneType" %>
<%@ page import="net.sourceforge.pinyin4j.format.HanyuPinyinVCharType" %>
<%@ page import="java.awt.Image" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.awt.Graphics" %>
<%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder" %>
<%@ page import="com.sun.image.codec.jpeg.JPEGCodec" %>

<%
response.setContentType("text/html; charset=UTF-8");
String root = pageContext.getServletContext().getRealPath("/");

if(!ServletFileUpload.isMultipartContent(request)){
	out.println(getError("请选择文件。"));
	return;
}


String iswater = request.getParameter("iswater");//是否添加水印0：不添加 1：添加

String uploadpath = request.getParameter("uploadpath");
if(uploadpath == null || "".equals(uploadpath)){
	String rootpath = request.getParameter("rootpath");
	if(rootpath == null && "".equals(rootpath)){
		out.println(getError("路径错误。"));
		return;
	}else{
		uploadpath = rootpath;
	}
}

String savePath = root + uploadpath;
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
	uploadDir.mkdirs();
}
//检查目录写权限
if(!uploadDir.canWrite()){
	out.println(getError("上传目录没有写权限。"));
	return;
}

boolean creatfolder = Boolean.parseBoolean(request.getParameter("creatfolder"));

if(creatfolder){
	Calendar cal = Calendar.getInstance();//使用日历类
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	String year = String.valueOf(cal.get(Calendar.YEAR));
	String day = sdf.format(new Date());
	File file1 = new File(savePath + year + "/");
	if(!file1.isDirectory()){
		file1.mkdir();
	}
	File file2 = new File(savePath + year + "/" + day + "/");
	if(!file2.isDirectory()){
		file2.mkdir();
	}
	savePath = savePath + year + "/" + day + "/";
    uploadpath = uploadpath + year + "/" + day + "/";
}

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
	FileItem item = (FileItem) itr.next();
	String fileName = item.getName();
	String newname = "";
	String autoname = request.getParameter("autoname");
	long fileSize = item.getSize();
	if (!item.isFormField()) {
		String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
		if(autoname != null && !"".equals(autoname) && "true".equals(autoname)){
			SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
			newname = s.format(new Date());
		}else{
			newname = HanyuToPinyin(fileName.substring(0 , fileName.lastIndexOf(".")));
		}
		try{
			File uploadedFile = new File(savePath, newname + fileExt);
			item.write(uploadedFile);
			Image image = ImageIO.read(uploadedFile);
			if (image != null && "1".equals(iswater)) {
				//加水印 
				setWaterMark(uploadedFile, root, savePath + newname + fileExt);
			}
		}catch(Exception e){
			e.printStackTrace();
			out.println(getError("上传文件失败。"));
			return;
		}
		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("serverurl", uploadpath + newname + fileExt);
		obj.put("message", "上传成功");
		out.println(obj.toString());
	}
}
%>
<%!
private String getError(String message) {
	JSONObject obj = new JSONObject();
	obj.put("error", 1);
	obj.put("message", message);
	return obj.toString();
}

private String HanyuToPinyin(String name){
	HanyuPinyinOutputFormat spellFormat = new HanyuPinyinOutputFormat();
	spellFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
	spellFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	spellFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
	String resutl = "";
	try {
		resutl = PinyinHelper.toHanyuPinyinString(name , spellFormat ,"").toString();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	return resutl;
}

/**
 * 将上传文件和水印文件合成带水印图片
 */
public static void setWaterMark(File targetFile, String rootPath, String path) throws IOException {
	//源文件
	Image src = ImageIO.read(targetFile);
	int width = src.getWidth(null);
	int height = src.getHeight(null);
	BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	Graphics g = image.createGraphics();
	g.drawImage(src, 0, 0, width, height, null);
	// 水印文件
	String watermark = rootPath + "resource/images/watermark/";
	InputStream pressIs = null;
	int x = 25;
    int y = 20;
    if (width >= 900)
    	pressIs = new FileInputStream(watermark + "watermark.png");
    else if (width >= 800)
    {
    	pressIs = new FileInputStream(watermark + "watermark9.png");
        x = 23;
        y = 18;
    }
    else if (width >= 700)
    {
        pressIs = new FileInputStream(watermark + "watermark8.png");
        x = 21;
        y = 16;
    }
    else if (width >= 600)
    {
        pressIs = new FileInputStream(watermark + "watermark7.png");
        x = 19;
        y = 14;
    }
    else if (width >= 500)
    {
        pressIs = new FileInputStream(watermark + "watermark6.png");
        x = 17;
        y = 12;
    }
    else if (width >= 400)
    {
        pressIs = new FileInputStream(watermark + "watermark5.png");
        x = 15;
        y = 10;
    }
    else if (width >= 300)
    {
        pressIs = new FileInputStream(watermark + "watermark4.png");
        x = 13;
        y = 8;
    }
    else if (width >= 200)
    {
        pressIs = new FileInputStream(watermark + "watermark3.png");
        x = 11;
        y = 6;
    }
    else
    {
        pressIs = new FileInputStream(watermark + "watermark2.png");
        x = 9;
        y = 4;
    }
	Image src_biao = ImageIO.read(pressIs);        
	int width_biao = src_biao.getWidth(null);        
	int height_biao = src_biao.getHeight(null);        
	g.drawImage(src_biao, width - width_biao - x, height - height_biao - y, width_biao, height_biao, null);        
	g.dispose();        
	FileOutputStream out = new FileOutputStream(path);        
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);        
	encoder.encode(image);        
	out.close();    
}
%>